<template>
	<div class="add-customer">
     <el-radio-group v-model="addType" @change="changeAddType" class="radio-group">
        <el-radio-button :label="1">选择客户</el-radio-button>
        <el-radio-button :label="2">创建客户</el-radio-button>
      </el-radio-group>
      <div class="btn-title">
         <span>客户信息</span>
       </div>
        <el-select
          style="margin-bottom: 12px"
          popper-class="customer-select"
          v-if="addType === 1"
					class="width-full"
          filterable
          remote
          :remote-method="remoteMethod"
          size="mini"
					:value="customerId"
					@change="changeSelect">
            <template v-for="one in customerList">
							<el-option
								:key="one._id"
								:value="one._id"
                :label="one.label"
								>
                <span style="margin-right:10px" :class="{'customer-disable': one.name === '空'}">{{one.name}}</span>
                <span :class="{'customer-disable': one.phone === '空'}">{{one.phone}}</span>
							</el-option>
						</template>
            <div v-if="!finishLoad" class="load-more" @click="loadmoreCustomer">再加载20条数据</div>
				</el-select>
      <customerForm v-if="addType === 2" :afterShow="true" ref="customerForm"></customerForm>
      <customerDetail v-if="addType === 1" :onlyReade="true" ref="customerDetail"></customerDetail>
     <div>
       <div class="btn-title">
         <span>联系人</span>
         <el-button v-if="addType === 1"  type="primary" size="mini" class="search-btn" @click="addContactor">新建联系人</el-button>
       </div>
      <el-select v-if="addType === 1" v-model="form.contactor" value-key="_id" class="width-full" size="mini" placeholder="请选择">
        <el-option
          v-for="item in contactorList"
          :key="item._id"
          :label="item.contactName + '【' + item.phone + '】'"
          :value="item">
        </el-option>
      </el-select>
      <div class="cust-rel" v-if="addType === 2">
        <div>
          <div class="label">联系人姓名</div>
          <el-input placeholder="请输入联系人姓名" size="mini" v-model="form.name"></el-input>
        </div>
        <div style="margin-top: 12px">
          <div class="label">联系人电话</div>
          <el-input placeholder="请输入联系人电话" size="mini" v-model="form.phone"></el-input>
        </div>
      </div>
     </div>

     <div>
       <div class="btn-title">
         <span>联系地址</span>
         <el-button type="primary" v-if="addType === 1" size="mini" class="search-btn" @click="addAddress">新建联系地址</el-button>
       </div>
       <el-select v-if="addType === 1" @change="changeAddress" v-model="form.addressObj" value-key="_id" class="width-full" size="mini" placeholder="请选择">
        <el-option
          v-for="item in addressList"
          :key="item._id"
          :label="areaMap[item.province] + '/' + areaMap[item.city] + '/' + areaMap[item.area] "
          :value="item">
        </el-option>
      </el-select>
       <el-cascader
            v-if="addType === 2"
            :clearable="true"
            style="width: 100%"
            size="small"
            :disabled="addType === 1 ? true : false"
            v-model="form.addressId"
            :options="areaList"
            :props="{ label: 'fullname', value: 'id', children: 'children' }"
            :show-all-levels="true"
            placeholder="请选择"
          >
          </el-cascader>
          <el-input
          style="margin-top: 12px"
            type="textarea"
            :disabled="addType === 1 ? true : false"
            :autosize="{ minRows: 2 }"
            placeholder="请填写详细地址"
            maxlength="100"
            size="mini"
            v-model="form.detailAddress"
          >
          </el-input>
     </div>
     <addressComp ref="addressComp" @updateAddr="updateAddr" :customerId="customerId" :noBtn="true"></addressComp>
     <person ref="person" @updatePerson="updatePerson" :customerId="customerId" :noBtn="true"></person>
	</div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Ref } from 'vue-property-decorator'
import { commonAction } from '@/utils/common'
import addressComp from '@/views/newCustomer/components/buttons/address.vue'
import person from '@/views/newCustomer/components/buttons/person.vue'
import customerForm from '@/views/newCustomer/drawer/addCustomer.vue'
import customerDetail from '@/views/newCustomer/components/customerEdit.vue'
// eslint-disable-next-line no-restricted-imports
import { cloneDeep } from 'lodash';
@Component({
  name: 'addCustomer',
  components: {
    customerForm,
    person,
    addressComp,
    customerDetail
  }
})
export default class extends Vue {
  [x: string]: any;
  @Ref() private readonly customerForm
  @Ref() private readonly customerDetail
  @Prop({ default: () => ([]) }) public areaList!: any;
  @Prop({ default: () => ({}) }) public areaMap!: any;
  private custTempType = 'detail'
  private addressList: any = []
  private onlyReade = true
  private customerId = ''
  private addType = 1
  private form = {
    addressObj: {} as any,
    name: '',
    phone: '',
    addressId: [] as any,
    detailAddress: '',
    customAddressId: '',
    contactor: {} as any
  }

  private contactorList: any = []
  private detailData: any = {}
  private customerList = []
  private page: number = 1
  private finishLoad: boolean = false
  private searchStr: string = ''
  private async changeSelect (val) {
    this.customerId = val
    this.getCustomerById()
    this.getCustomerRel()
    this.getCustomerAddress()
    // 每次选择后将下拉更新到初始值
    this.searchStr = ''
    this.page = 1
    this.finishLoad = false
    this.getCustomerList()
  }

  private loadmoreCustomer () {
    if (!this.finishLoad) {
      this.page += 1
      this.getCustomerList(this.searchStr)
    }
  }

  private changeAddress () {
    this.form.detailAddress = this.form.addressObj.detailAddress
  }

  public submit () {
    if (this.addType === 2) {
      this.save()
    } else {
      this.relaCustomer()
    }
  }

  private relaCustomer () {
    const { contactor: { _id, contactName, phone, contactEmail }, addressObj: { detailAddress, city, province, area }, customAddressId } = this.form
    const sendData = {
      contactName,
      phone,
      contactEmail,
      customContactId: _id,
      province,
      city,
      area,
      detailAddress,
      customAddressId: this.form.addressObj._id,
      customId: this.customerId
    }
    const msg = Object.assign({}, this.detailData, sendData)
    this.$emit('addCustSuccess', msg)
  }

  public save () {
    const { status, newForm } = this.customerForm.checkForm()
    // 处理 文本框多个手机号、邮箱、微信号、qq 为空的情况
    const mulInput = ['mobile', 'qq', 'wechat', 'email', 'attachments']
    mulInput.map(mul => {
      if (!newForm[mul]) {
        newForm[mul] = []
      }
    })
    if (status) {
      const params = { url: '/server-crm/action/customer/add', method: 'POST', data: { ...newForm, createMethod: 'WORKORDER' } }
      commonAction(params).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
          const customerId = res.data._id
          const { name, phone, detailAddress, addressId } = this.form
          const sendData = {
            province: addressId.length && addressId[0],
            city: addressId.length && addressId[1],
            area: addressId.length && addressId[2],
            isDefault: 1,
            detailAddress,
            customerId
          }
          let customerMsg = Object.assign({}, res.data, { customId: res.data._id })
          if (name && addressId.length) {
            const addContactor = commonAction({ url: '/server-crm/action/contactor/add', method: 'POST', data: { contactName: name, phone, isDefault: 1, customerId } })
            const addAddress = commonAction({ url: '/server-crm/action/address/add', method: 'POST', data: sendData })
            Promise.all([addContactor, addAddress]).then(([res1, res2]) => {
              if (res1.success && res2.success) {
                customerMsg = Object.assign({}, customerMsg, res2.data, res1.data, { customContactId: res1.data._id, customAddressId: res2.data._id })
                this.$emit('addCustSuccess', customerMsg)
              }
            })
          } else if (name) {
            commonAction({ url: '/server-crm/action/contactor/add', method: 'POST', data: { contactName: name, phone, isDefault: 1, customerId } }).then(res1 => {
              if (res1.success) {
                customerMsg = Object.assign({}, customerMsg, res1.data, { customContactId: res1.data._id })
                this.$emit('addCustSuccess', customerMsg)
              }
            })
          } else if (addressId.length) {
            commonAction({ url: '/server-crm/action/address/add', method: 'POST', data: sendData }).then(res2 => {
              if (res2.success) {
                customerMsg = Object.assign({}, customerMsg, res2.data, { customAddressId: res2.data._id })
                this.$emit('addCustSuccess', customerMsg)
              }
            })
          } else {
            customerMsg = Object.assign({}, customerMsg, { customContactId: '', customAddressId: '' })
            this.$emit('addCustSuccess', customerMsg)
          }
        }
      })
    }
  }

  private async changeAddType (val) {
    this.addType = val
    if (val === 2) {
      this.contactorList = []
      this.form.contactor = {}
      this.onlyReade = false
      this.form.detailAddress = ''
      this.form.addressId = []
      this.customerId = ''
      this.custTempType = 'addCcustomer';
      await this.$getCache('/server-crm/action/customer/common/panel/insert', ['customerInputConfig'], false, false, false, 'GET', false, 'data.fields') // 录入面板配置
      this.$nextTick(() => {
        this.customerForm.initData() // 初始化录入表单
      })
    } else {
      this.onlyReade = true
      this.custTempType = 'detail';
      if (this.customerId) {
        this.getCustomerById()
      }
    }
  }

  public clearForm () {
    if (this.addType === 2) { // 若之前是新增客户，再次打开窗口的时候，要清空表单
      this.changeAddType(2)
    }
  }

  private updatePerson (res) {
    this.form.contactor = res
    this.contactorList.push(res)
  }

  private updateAddr (res: any) {
    this.form.addressObj = res
    this.addressId = [res.province, res.city, res.area]
    this.form.detailAddress = res.detailAddress
    this.addressList.push(res)
  }

  private addAddress () {
    if (this.customerId) {
      (this.$refs as any).addressComp.openDialog()
    } else {
      this.$message.error('请选择客户！')
    }
  }

  private getCustomerById () {
    commonAction({
      url: '/server-crm/action/customer/' + this.customerId,
      method: 'get'
    }).then(async res => {
      if (res.success) {
        this.detailData = res.data || {};
        await this.$getCache('/server-crm/action/customer/common/panel/detail', ['customerDetailConfig'], false, false, false, 'GET', false, 'data.fields')
        this.$nextTick(() => {
          this.customerDetail.initData(this.detailData)
        })
      }
    })
  }

  private addContactor () {
    if (this.customerId) {
      (this.$refs as any).person.openDialog({})
    } else {
      this.$message.error('请选择客户！')
    }
  }

  private getCustomerAddress () {
    commonAction({
      url: '/server-crm/action/address/listAll',
      method: 'post',
      data: {
        customerId: this.customerId
      }
    }).then(res => {
      if (res.success) {
        this.addressList = res.data?.list || []
        this.addressList.map(item => {
          if (item.isDefault === 1) {
            this.form.addressObj = cloneDeep(item)
            this.form.detailAddress = cloneDeep(item.detailAddress)
          }
        })
      }
    })
  }

  private getCustomerRel () {
    commonAction({
      url: '/server-crm/action/contactor/listAll',
      method: 'post',
      data: {
        customerId: this.customerId
      }
    }).then(res => {
      if (res.success) {
        this.contactorList = res.data?.list || []
        this.contactorList.map(item => {
          if (item.isDefault === 1) {
            this.form.contactor = item
          }
        })
      }
    })
  }

  private getCustomerList (searchStr = '') {
    const actionData = {
      limit: 20,
      page: this.page,
      keyword: searchStr
    }
    commonAction({ url: '/server-crm/action/customer/query', method: 'POST', data: actionData }).then(res => {
      if (res.success) {
        if (res.data.count < 20) {
          this.finishLoad = true
        } else {
          this.finishLoad = false
        }
        const result = res.data.list.map(item => {
          let phone = '空'
          let name = '空'
          if (item.mobile && Array.isArray(item.mobile)) {
            phone = item.mobile.map(x => x.value).join('、')
            if (phone === '') {
              phone = '空'
            }
          }
          if (item.name) {
            name = item.name
          }
          item.name = name
          item.phone = phone
          item.label = name + ' ' + phone
          return item
        })
        if (this.page === 1) {
          this.customerList = result || []
        } else {
          this.customerList = this.customerList.concat(result)
        }
      }
    })
  }

  private beforeMount () {
    this.getCustomerList()
    this.$getCache('/server-crm/action/customer/common/labels', ['customerAllLabels'], true, false, false, 'GET', false, 'data') // 客户标签
  }

  private remoteMethod (query) {
    // 每次模糊搜索从第一页开始
    this.page = 1
    this.searchStr = query
    this.getCustomerList(query)
  }
}
</script>
<style lang="stylus" scoped>
.add-customer
  margin-bottom 16px
  font-size 12px
  .label
    color #303753
    padding 0 0 12px 0
  .btn-title
    display flex
    justify-content space-between
    align-items center
    margin-bottom 12px
    margin-top 24px
    padding-top 10px
    border-top 1px dashed #dcdfe6
    span
      font-weight 500
.customer-select
  .el-select-dropdown__item
    width 553px
  .customer-disable
    color: #c0c4cc;
  .load-more
    height: 32px;
    line-height: 32px;
    text-align: center;
    color: $fc-gray4;
    cursor: pointer;
    font-size: 14px;
  .load-more:hover
    color $hover-blue
</style>
